package cn.fudong.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.fudong.bos.domain.constant.Constants;
import cn.fudong.bos.utils.MailUtils;
import cn.fudong.crm.domain.Customer;

/**
 * 
 * @description:客户登录注册管理
 * @author ：d_fu
 * @date 创建时间：2018年3月15日 下午6:58:03
 *
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

	// 注入jmsTemplate
	@Autowired
	private JmsTemplate jmsTemplate;

	// 发送短信验证码：customer_sendSms
	@Action(value = "customer_sendSms")
	public String sendSms() throws Exception {
		// 生产验证码
		final String randomCode = RandomStringUtils.randomNumeric(4);
		// 将验证码保存到session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		// 把短信内容打印到控制台
		System.out.println("手机号:" + model.getTelephone() + "生成手机验证码为：" + randomCode);

		// 给客户发短息
		// boolean result = SMS_AlYun_High_Test.sendSms(model.getTelephone(),
		// randomCode);

		// 发送消息给到ActiveMQ
		jmsTemplate.send("fudong_bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("randomCode", randomCode);

				return mapMessage;
			}
		});

		return NONE;

	}

	// 用户注册 customer_regist
	// 属性驱动获取chanckcode
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	// 注入一个redis模板
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 从session中取出验证码
		String checkcodeSession = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		// 判断
		if (!checkcodeSession.equals(checkcode) || checkcodeSession == null || checkcode == null) {
			// 不同就跳转到本页面，并给出提示
			System.out.println("短信验证码错误...");
			// 短信验证码错误
			return INPUT;
		}
		// 发送webservice给crm存入
		WebClient.create("http://localhost:9996/fudong_crm_management/services/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);

		// 发送一封邮件给客户，携带电话号码，和邮箱的注册码
		// 生成激活码

		String activecode = RandomStringUtils.randomNumeric(32);
		System.out.println("邮件激活码为:" + activecode);

		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
				+ model.getTelephone() + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		// 将邮件信息存入redies中，设置24小时失效
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);

		System.out.println("注册成功");
		return SUCCESS;

	}

	// 属性驱动获取页面带来的验证码
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	// 邮箱激活customer_activeMail
	@Action("customer_activeMail")
	public String ctiveMail() throws Exception {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");

		// 拿到邮件传来的激活码
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		System.out.println("已获取到激活码：" + activecodeRedis);

		// 判断激活码是否失效
		if (activecodeRedis == null || !activecode.equals(activecodeRedis)) {
			// 激活码失效
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 激活码有效
			// 连接webservice查询状态，判断是否重复激活
			Customer customer = WebClient
					.create("http://localhost:9996/fudong_crm_management/services/customerService/customer/findbytelephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);

			if (customer.getType() == null || customer.getType() != 1) {
				// 没有激活连接webservice,更改type=1
				WebClient
						.create("http://localhost:9996/fudong_crm_management/services/customerService/customer/updatetype/"
								+ model.getTelephone())
						.put(null);

				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				// 已经激活响应提示
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
			}
			// 删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}

		return NONE;

	}

	// 客户登录
	@Action(value = "customer_login", results = { @Result(name = "login", location = "login.html", type = "redirect"),
			@Result(name = "success", location = "index.html#/myhome", type = "redirect") })
	public String Login() {
		Customer customer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customer/login?telephone="
						+ model.getTelephone() + "&password=" + model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer == null) {
			// 登录失败
			return LOGIN;
		} else {
			// 登录成功
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			return SUCCESS;
		}

	}
}
